package com.itheima.service.impl;

import cn.hutool.core.util.IdUtil;
import com.itheima.common.PageInfo;
import com.itheima.dto.SetmealDto;
import com.itheima.mapper.CategoryMapper;
import com.itheima.mapper.SetmealMapper;
import com.itheima.pojo.Category;
import com.itheima.pojo.Setmeal;
import com.itheima.pojo.SetmealDish;
import com.itheima.service.SetmealService;
import com.itheima.thread.TokenThreadUtils;
import com.itheima.vo.SetmealByIdVo;
import com.itheima.vo.SetmealVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class SetmealServiceImpl implements SetmealService {

    @Autowired
    private SetmealMapper setmealMapper;


    @Autowired
    private CategoryMapper categoryMapper;


    //添加套餐
    @Transactional
    @Override
    public boolean addSetmeal(SetmealDto setmealDto) {
        String id = IdUtil.getSnowflakeNextIdStr();
        setmealDto.setId(id);

        Setmeal setmeal = new Setmeal();

        BeanUtils.copyProperties(setmealDto, setmeal);

        String cuid = TokenThreadUtils.threadLocal.get().getId();
        setmeal.setCreateUser(cuid);

        int res = setmealMapper.addSetmeal(setmeal);

        //加入菜品
        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();

        List<SetmealDish> newlist = new ArrayList<>();
        if (!CollectionUtils.isEmpty(setmealDishes)) {
            for (SetmealDish item : setmealDishes) {
                if (item == null) {
                    continue;
                }
                SetmealDish setmealdish = new SetmealDish();

                BeanUtils.copyProperties(item, setmealdish);

                setmealdish.setId(IdUtil.getSnowflakeNextIdStr());

                setmealdish.setSetmealId(setmeal.getId());

                setmealdish.setCreateTime(LocalDateTime.now());
                setmealdish.setUpdateTime(LocalDateTime.now());

                setmealdish.setCreateUser(cuid);
                setmealdish.setUpdateUser(cuid);

                newlist.add(setmealdish);
            }
        }
        int rs = setmealMapper.batchInsertSetmealDish(newlist);
        if (rs != newlist.size()) {
            throw new RuntimeException("口味套餐菜品失败");
        }
        return res == 1;
    }


    @Transactional(rollbackFor = RuntimeException.class)
    @Override
    public boolean updateSetmeal(SetmealDto setmealDto) {
        if (setmealDto == null) {
            throw new RuntimeException("参数不能为空");
        }

        //创建新的套餐容器
        Setmeal setmeal = new Setmeal();

        String cuid = TokenThreadUtils.threadLocal.get().getId();

        //从setmealDto提取套餐相关数据，封装到setmeal对象中
        BeanUtils.copyProperties(setmealDto, setmeal);


        setmeal.setCreateUser(cuid);
        setmeal.setUpdateUser(cuid);
        setmeal.setUpdateTime(LocalDateTime.now());

        int res = setmealMapper.updateSetmeal(setmeal);
        if (res != 1) {
            log.error("套餐修改失败");
        }


        //删除套餐下关联的菜品
        int total = setmealMapper.countSetmealDish(setmealDto.getId());
        if (total > 0) {
            int removeRes = setmealMapper.removeSetmealDishById(setmealDto.getId());
            if (removeRes != total) {
                log.error("套餐菜品删除失败");
                return false;
            }
        }


        //从setmealDto提取套餐菜品相关数据，封装到setmealDish对象中
        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();

        List<SetmealDish> newlist = new ArrayList<>();
        if (!CollectionUtils.isEmpty(setmealDishes)) {
            for (SetmealDish item : setmealDishes) {
                if (item == null) {
                    continue;
                }
                //2.1将接收到的参数 转成SetmealDish对象结构
                SetmealDish dish = new SetmealDish();
                BeanUtils.copyProperties(item, dish);
                dish.setId(IdUtil.getSnowflakeNextIdStr());

                dish.setSetmealId(setmealDto.getId());


                dish.setCreateUser(cuid);
                dish.setUpdateUser(cuid);

                newlist.add(dish);

            }
        }

        int rs = setmealMapper.batchInsertSetmealDish(newlist);
        if (rs != newlist.size()) {
            throw new RuntimeException("套餐菜品添加失败");
        }

        return true;
    }

    @Override
    public boolean status(Integer status, List<String> ids) {
        boolean res = setmealMapper.status(status, ids);
        return res;
    }

    @Override
    @Transactional
    public boolean deleteSetmeal(List<String> ids) {
        //删除套餐
        boolean res = setmealMapper.deleteSetmeal(ids);
        //删除套餐对应菜品
        setmealMapper.deleteSetmealDish(ids);
        return res;
    }

    @Override
    public List<Setmeal> getSetmealByIdStatus(String categoryId, Integer status) {

        List<Setmeal> setmeal = setmealMapper.getSetmealByIdStatus(categoryId,status);

        return setmeal;
    }

    @Override
    public SetmealByIdVo getMobileSetmealById(String id) {
        SetmealByIdVo setmealById = setmealMapper.getSetmealById(id);
        List<SetmealDish> setmealDishById = setmealMapper.getSetmealDishById(id);
        setmealById.setSetmealDishes(setmealDishById);
        return setmealById;
    }


    //分页查询套餐    下面的<Dish>是因为PageInfo自定义了一个泛型<T>
    @Override
    public PageInfo<SetmealVo> page(String name, Integer page, Integer pageSize) {
        //创建一个容器
        PageInfo<SetmealVo> pageInfo = new PageInfo<SetmealVo>();
        //分页公式    第几页 = （第几页-1） * 一页的个数
        Integer start = (page - 1) * pageSize;
        List<SetmealVo> setmeals = setmealMapper.page(name, start, pageSize);

        //找到分类名称写入页面
        for (SetmealVo setmeal : setmeals) {
            Category categoryById = categoryMapper.getCategoryById(setmeal.getCategoryId());
            String categoryName = categoryById.getName();
            setmeal.setCategoryName(categoryName);
        }

        //records：当前页面内容，是个数组[]
        pageInfo.setRecords(setmeals);
        //size：每页显示条数
        pageInfo.setSize(pageSize);
        //current：当前页码
        pageInfo.setCurrent(page);

        //计算 total(总条数)(通过名字) 的方法
        long count = setmealMapper.countSetmeal();

        //total：总条数
        pageInfo.setTotal(count);
        return pageInfo;
    }

    @Override
    public SetmealByIdVo getSetmealById(String id) {

        //调用根据id查询套餐（无口味）  并 将返回值写入setmealByIdVo
        SetmealByIdVo setmealById = setmealMapper.getSetmealById(id);

        //获取口味   注：sql语句内，要通过setmeal_dish的setmeal_id去匹配传入的菜品id
        List<SetmealDish> setmealDishes = setmealMapper.getSetmealDishById(id);

        //将菜品添加进去SetmealByIdVo
        setmealById.setSetmealDishes(setmealDishes);

        return setmealById;


    }


}
